import { getResponseMessage } from "@mallfoundry/client/message"
import { Member, MemberService } from "@mallfoundry/store/member"
import { Card, Col, message as antMessage, Row } from "antd"
import * as React from "react"
import { useHistory, useParams } from "react-router-dom"
import Page from "../../components/page"
import { useLoading } from "../../hooks/loading"
import { useMember } from "../../hooks/member"
import MemberForm from "./member-form"

export default function MemberEdit() {
  const { storeId, memberId } = useParams<{ storeId: string, memberId: string }>()
  const history = useHistory()
  const {
    loading: memberLoading,
    member,
  } = useMember(storeId, memberId)

  const [loading, setLoading] = useLoading(memberLoading)

  function finish(values: Member) {
    setLoading(loading)
    MemberService.updateMember(values)
      .then(() => {
        antMessage.success("保存成功")
      })
      .then(() => history.goBack())
      .catch(error => antMessage.error(getResponseMessage(error)))
      .finally(() => setLoading(false))
  }

  return (
    <div>
      <Page.Header title="会员编辑" ghost={false}/>
      <Page.Content>
        <Card>
          <Row>
            <Col span={24}>
              <MemberForm idReadonly loading={loading} member={member} onFinish={finish}
                          onCancel={() => history.push(`/stores/${storeId}/members`)}/>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
